/*
 * Copyright (c) 2018-2999 北京小象智慧信息科技有限公司 All rights reserved.
 *
 * https://www.xiaoxiangai.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.PaymentDto;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.vo.UserVO;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PageAdapter;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.dao.YqmMapper;
import com.yami.shop.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author lgh on 2018/09/11.
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private  String yqmSucceed ="999";//用户已经绑定邀请码

    private String yqmSuccess ="000";//用户绑定邀请码成功
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private YqmMapper yqmMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private  UserService userService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private OldUserService oldUserService;



    @Override
    public User getUserByUserId(String userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public User getUserByYqm(String yqm) {
        return userMapper.getUserByyqm(yqm);
    }

    @Override
    @Transactional(rollbackFor = Exception.class )
    public String  setyqmLog(User user) {
        //为当前用户绑定上级用户
        userMapper.updateUserByuserid(user.getUserId(),user.getPuserid());
        //查询邀请码表中该用户有没有绑定记录
        Yqm yqmflag = yqmMapper.getYqmByyqmUserid(user.getYqm(),user.getUserId());
        if(yqmflag!=null){
            return yqmSucceed;
        }else{
            //向邀请码表中增加数据
            Yqm yqm = new Yqm();
            yqm.setUserid(user.getPuserid());
            yqm.setYqmuserid(user.getUserId());
            yqm.setYqm(user.getYqm());
            yqm.setStatus(1);
            yqm.setCreate_time(new Date());
            yqmMapper.insert(yqm);
            return yqmSuccess;
        }


    }

    @Override
    public String getBizUserId(String userId) {
        return userMapper.getBizUserId(userId);
    }

    @Override
    public Long getAppConnectId(String userId) {
        return userMapper.getAppConnectId(userId);
    }

    @Override
    public String getUserByAppConnectId(Long id) {
        return userMapper.getUserByAppConnectId(id);
    }

    @Override
    public List<User> getUserByPuserid(String userId) {
        return userMapper.getUserByPuserid(userId);
    }

    @Override
    public String getOrderNumber(String userId,String puserId) {
        return userMapper.getOrderNumber(userId,puserId);
    }

    @Override
    public User getByid(String userId){
        return userMapper.selectById(userId);
    }

    @Override
    public IPage<User> getMember(Page<User> page,String tel) {
         List<User> userList = userMapper.getMember(new PageAdapter(page),tel);
         page.setRecords(userList);
         int memberNumber = userMapper.getMemberNumber(new PageAdapter(page),tel);
         page.setSize(memberNumber);
         return page;
    }

    @Override
    public List<User> getUserByPhone(String phone){
        return userMapper.getUserByPhone(phone);
    }

    @Override
    public void addNewMember(User user) {
        userMapper.addNewMember(user);
    }

    @Override
    @Transactional
    public String payMoneyByAccount(String orderNumber, Double payMoney) {
        //更新订单类型支付状态
        Order order = orderService.getOrderByOrderNumber(orderNumber);
        order.setStatus(5);

        //扣除用户账户余额
        String userId = order.getUserId();
        User user = userService.getUserByUserId(userId);
        Double userAccount = user.getUserAccount();
        BigDecimal currentAmount = new BigDecimal(userAccount);
        BigDecimal payAmount = new BigDecimal(payMoney);
        //查询老用户账户余额
        Long shopId = order.getShopId();
        OldUser oldUser = oldUserService.getOldUserByShopId(userId,shopId);
        if(order.getMixedPayment()==1){
            //计算需要账户余额需要支付的金额
            BigDecimal oldAccount = order.getOldAccountPay();
            if(oldAccount.compareTo(new BigDecimal("0"))>-1){
                Double remainAccount = Arith.sub(order.getActualTotal(),oldAccount.doubleValue());
                //计算新账户剩余金额
                if(currentAmount.compareTo(new BigDecimal(remainAccount).setScale(2,BigDecimal.ROUND_HALF_UP))>-1){
                    Double newAccount = Arith.sub(currentAmount.doubleValue(),remainAccount);
                    user.setUserAccount(newAccount);
                    userService.saveOrUpdate(user);

                    oldUser.setAccount(new BigDecimal("0"));
                    oldUserService.saveOrUpdate(oldUser);
                }else{
                    return "支付余额不足！";
                }
                order.setNewAccountPay(new BigDecimal(remainAccount));
                order.setPayType(5);
            }
        }else{
            if(oldUser!=null){
                BigDecimal oldAccount = oldUser.getAccount();
                if(oldAccount.compareTo(payAmount)>-1){
                    BigDecimal remainMoney = oldAccount.subtract(payAmount);
                    oldUser.setAccount(remainMoney);
                    oldUserService.saveOrUpdate(oldUser);
                    order.setPayType(4);
                }else{
                    if(currentAmount.compareTo(payAmount)>-1){
                        double remainMoney =  Arith.sub(userAccount,payMoney);
                        user.setUserAccount(remainMoney);
                        userService.saveOrUpdate(user);
                        order.setPayType(3);
                    }else{
                        return "用户账户余额不足!";
                    }
                }
            }else{
                if(currentAmount.compareTo(payAmount)>-1){
                    double remainMoney =  Arith.sub(userAccount,payMoney);
                    user.setUserAccount(remainMoney);
                    userService.saveOrUpdate(user);
                    order.setPayType(3);
                }else{
                    return "用户账户余额不足!";
                }
            }
        }
        orderService.updateById(order);


        //商品库存数量减去已支付成功的商品数量
        List<OrderItem> orderItemList =orderItemService.getOrderItemsByOrderNumber(orderNumber);
        if(CollectionUtils.isNotEmpty(orderItemList)){
            for(OrderItem orderItem:orderItemList){
                Long prodId = orderItem.getProdId();
                int prodCount  = orderItem.getProdCount();
                //查询对应的商品数量
                Product product = productService.getProductByProdId(prodId);
                int totalStocks = product.getTotalStocks();
                int remainStock =  totalStocks - prodCount;
                product.setTotalStocks(remainStock);
                productService.saveOrUpdate(product);

                //sku库存量修改
                Long skuId = orderItem.getSkuId();
                Sku sku = skuService.getSkuBySkuId(skuId);
                int stocks =  sku.getStocks();
                //剩余库存量
                int leftStock =  stocks - prodCount;
                sku.setStocks(leftStock);
                skuService.saveOrUpdate(sku);
            }
        }
        //发送会员消费短信提醒
       // smsLogService.sendSmsToMemberAfterConsumption(user.getUserMobile(),order.getOrderNumber());
        return "success";
    }

    @Override
    public List<User> getUserByMobileOrNickName(String searchField) {
        return userMapper.getUserByMobileOrNickName(searchField);
    }

    @Override
    public User selectUserByPhoneOne(String mobile){
        return userMapper.selectUserByPhoneOne(mobile);
    }

    @Override
    @Transactional
    public void updateUserAccountByBuCha(PaymentDto paymentDto) {
        String orderNumber = paymentDto.getOrderNumber();
        Order order = orderService.getOrderByOrderNumber(orderNumber);
        Double oldAccountPay = paymentDto.getOldAccountPay();
        Double newAccountPay = paymentDto.getNewAccountPay();
        String userId = order.getUserId();
        User user = userService.getUserByUserId(userId);
        Long shopId = order.getShopId();
        if(oldAccountPay!=null&&new BigDecimal(oldAccountPay).compareTo(new BigDecimal(0))!=0) {
            order.setOldAccountPay(new BigDecimal(oldAccountPay));
            //查询出老账户余额
//            OldUser oldUser = oldUserService.getOldUserByShopId(userId,shopId);
//            BigDecimal account = new BigDecimal(0.00);
//            if(oldUser!=null){
//                 account = oldUser.getAccount();
//            }
//            BigDecimal oldAccountPaybd = new BigDecimal(oldAccountPay).setScale(2,BigDecimal.ROUND_HALF_UP);
//            if(account.compareTo(oldAccountPaybd)>-1){
//                Double newOldAccount = Arith.sub(account.doubleValue(),oldAccountPay);
//                oldUser.setAccount(new BigDecimal(newOldAccount));
//                oldUserService.saveOrUpdate(oldUser);
//            }
        }else if(newAccountPay!=null&&new BigDecimal(newAccountPay).compareTo(new BigDecimal(0))!=0){
            order.setNewAccountPay(new BigDecimal(newAccountPay));
            Double account = user.getUserAccount();
            BigDecimal newAccountPaybd = new BigDecimal(newAccountPay);
            if(new BigDecimal(account).compareTo(newAccountPaybd)>-1){
                Double newAccount = Arith.sub(account,newAccountPay);
                user.setUserAccount(newAccount);
                userService.saveOrUpdate(user);
            }
        }
        order.setMixedPayment(1);
        orderService.saveOrUpdate(order);

    }
}
